/**
 * 表达式解析
 */
import { chunk, zip, toPair, toBins } from './utils'

/**
 * 支持的表达式类型
 * match
 * literals
 * interpolate
 * step
 */
const stopper: any = {
  literal: (expression: any) => [[...expression, ...expression]],
  interpolate: (expression: any) => chunk(expression.slice(2), 2),
  // match: (expression: any) => chunk(expression.slice(1), 2).map(toPair),
  match: (expression: any) =>
    chunk(expression.slice(1), 2).map((element) => toPair(element)),
  step: (expression: any) =>
    toBins([...chunk(expression.slice(2), 2), [null, expression[1]]]),
}

/**
 * 判断是都是表达式
 * @param expression
 * @returns boolean
 */
const isExpression = (expression: any) =>
  Array.isArray(expression) &&
  expression.length &&
  typeof expression[0] === 'string'

/**
 * 解析表达式
 * @param input 输入表达式  *-color *-radius *-image
 */
const parse = (input: any) => {
  let filterExpression: any = input
  // 防止有其他情况
  if (isExpression(input) && input.includes('case')) {
    filterExpression = input[input.length - 1]
  }
  const [name, ...otherArguments] = isExpression(filterExpression)
    ? filterExpression
    : ['literal', filterExpression]
  if (!stopper[name]) {
    return null
  }
  const stops: any = stopper[name](otherArguments)
  // @ts-ignore
  const [inputs, outputs] = zip(...stops)
  const min = Math.min(...inputs.flat(2))
  const max = Math.max(...inputs.flat(2))
  return { name, stops, inputs, outputs, min, max }
}

export default { isExpression, parse }
